package com.tanhua.server.Interceptor;

import com.alibaba.fastjson.JSON;
import com.mongodb.client.result.UpdateResult;
import com.tanhua.domain.db.User;
import com.tanhua.domain.mongo.FreezingUser;
import com.tanhua.domain.mongo.UserLoveState;
import com.tanhua.server.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;

/**
 * 拦截器是需要实现
 */
@Component
@Slf4j
public class TokenInterceptor implements HandlerInterceptor {

    @Autowired
    private UserService userService;
    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    private static final String REDIS_KEY = "FREEZE_USER_";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {


        //1.先获取token
        String token = request.getHeader("Authorization");
        log.info("token======"+token+"==========统一处理的token============="+request.getRequestURI());
        //2. 如果没有携带token，代表该用户没有登陆
        if(token==null){
            response.setStatus(401);
            return false;
        }
        //3. 如果已经携带了token，但是token找不到用户对象
        User user = userService.findUserByToken(token);
        if(user==null){
            response.setStatus(401);
            return false;
        }
        ValueOperations<String, String> ops = redisTemplate.opsForValue();
        String freezeUser = ops.get(REDIS_KEY + user.getId());
        if (!StringUtils.isEmpty(freezeUser)){
            FreezingUser freezingUser = JSON.parseObject(freezeUser, FreezingUser.class);
            if (freezingUser.getFreezingRange().equals(1)) {
//                throw  new RuntimeException("你的账号已经冻结了...");
                response.setStatus(401);
                Long created = freezingUser.getCreated();
                String format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(created);
                response.setContentType("text/html;charset=UTF-8");
                response.getWriter().println("账号"+format+"已被封号"+"\r\n"
                        +"原因："+freezingUser.getFrozenRemarks());
                return false;
            }
        }

        //4. token找到对应的用户，代表着该用户是登陆的。
        //问题： 如何把User对象传递给controller与service...
        UserHolder.set(user);
        //判断路径是否访问love接口，如果是同个用户
        Query query=new Query(Criteria.where("userId").is(UserHolder.getUserId()));
        UserLoveState one = mongoTemplate.findOne(query, UserLoveState.class);
        if(one==null){
            UserLoveState userLoveState=new UserLoveState();
            userLoveState.setUserId(UserHolder.getUserId());
            userLoveState.setIsPeachblossom(0);
            userLoveState.setIslove(0);
            mongoTemplate.save(userLoveState);
        }
        String requestURI = request.getRequestURI();
        UserLoveState one1 = mongoTemplate.findOne(query, UserLoveState.class);
        //如果是peachblossom则记录在数据库
        if(request.getMethod().equals("GET")&&requestURI.substring(requestURI.lastIndexOf("/")+1).equals("peachblossom")){
            Update update=new Update();
            update.set("isPeachblossom",1);
            UpdateResult updateResult = mongoTemplate.updateFirst(query, update, UserLoveState.class);
        }else {
            //如果不是peachblossom,判断是否被改为1是的话，判断这次接口访问是否是love或者unlove
            if(one1.getIsPeachblossom()==1){
                if(requestURI.substring(requestURI.lastIndexOf("/")+1).equals("love")||requestURI.substring(requestURI.lastIndexOf("/")+1).equals("unlove")){
                    Update update=new Update();
                    update.set("islove",1);
                    mongoTemplate.updateFirst(query,update,UserLoveState.class);
                }else {
                    //如果不是love获取unlove则直接归初始化
                    Update update=new Update();
                    update.set("isPeachblossom",0);
                    update.set("islove",0);
                    mongoTemplate.updateFirst(query, update, UserLoveState.class);
                }
            }
        }
        return true;
    }
}
